<template>
  <div class="administration">
    <el-tooltip
      placement="top-start"
      content="统计规则：统计各个系统类别下事业单位的数量"
    >
      <h5>事业单位</h5>
    </el-tooltip>
    <div class="total">
      <div class="tdata" v-html="sydwCount"></div>
    </div>
    <!-- 3D饼图部分-->
    <div class="pie" id="sydwpie"></div>
  </div>
  <el-dialog
  :draggable="true"
    :title="despTitle"
    v-model="dialogVisible"
    width="50%"
    destroy-on-close
  >
    <!-- <div class="mg-chart" ref="mgcharts"></div> -->
    <SydwPieChild
      :depCode="depCode"
      :depName="depName"
    ></SydwPieChild>
  </el-dialog>
</template>

<script>
var myChart;
import Sever from "@/api/selfApi";
import SydwPieChild from "@/components/home/SydwPieChild.vue";
export default {
  name: "HomeSydwPie",
  components:{
  	  Sever,
  	  SydwPieChild
  },
  data() {
    return {
		dialogVisible: false,
		depName:"",
		despTitle:"",
		depCode:"36%",
      sydwCount: "总计：<span>0</span>",
      sydwdata: [
        {
          name: "党委",
          value: 15,
          itemStyle: { color: "#637FEA" },
          startRatio: 0,
          endRatio: 0.15,
        },
        {
          name: "人大",
          value: 25,
          itemStyle: { color: "#3919FB" },
          startRatio: 0.15,
          endRatio: 0.4,
        },
        {
          name: "政府",
          value: 10,
          itemStyle: { color: "#B35AFF" },
          startRatio: 0.4,
          endRatio: 0.5,
        },
        {
          name: "政协",
          value: 20,
          itemStyle: { color: "#5AADD4" },
          startRatio: 0.5,
          endRatio: 0.7,
        },
        {
          name: "法院",
          value: 15,
          itemStyle: { color: "#EDCC31" },
          startRatio: 0.5,
          endRatio: 0.7,
        },
        {
          name: "检察院",
          value: 22,
          itemStyle: { color: "#FF8421" },
          startRatio: 0.5,
          endRatio: 0.7,
        },
        {
          name: "群团",
          value: 5,
          itemStyle: { color: "#15B309" },
          startRatio: 0.5,
          endRatio: 0.7,
        },
        {
          name: "民主党派",
          value: 10,
          itemStyle: { color: "#25BD97" },
          startRatio: 0.5,
          endRatio: 0.7,
        },
      ],
    };
  },
  mounted() {
    this.refreshData("36%");
  },
  methods: {
    initEcharts() {
      myChart.hideLoading();
      const option = this.getPie3D(this.sydwdata, 0);
      myChart.clear();
      myChart.setOption(option);
	  myChart.on("click", (param) => {
	  		  console.log(param);
	    this.depName = param.seriesName;
	    this.despTitle = param.seriesName + "详细机构情况";
	    this.dialogVisible = true;
	  });
      // 响应式变化
      window.addEventListener("resize", () => myChart.resize(), false);
    },
    getParametricEquation(
      startRatio,
      endRatio,
      isSelected,
      isHovered,
      k,
      height
    ) {
      // 计算
      let midRatio = (startRatio + endRatio) / 2;

      let startRadian = startRatio * Math.PI * 2;
      let endRadian = endRatio * Math.PI * 2;
      let midRadian = midRatio * Math.PI * 2;

      // 如果只有一个扇形，则不实现选中效果。
      if (startRatio === 0 && endRatio === 1) {
        isSelected = false;
      }

      // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
      k = typeof k !== "undefined" ? k : 1 / 3;

      // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
      let offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
      let offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;

      // 计算高亮效果的放大比例（未高亮，则比例为 1）
      let hoverRate = isHovered ? 1.05 : 1;

      // 返回曲面参数方程
      return {
        u: {
          min: -Math.PI,
          max: Math.PI * 3,
          step: Math.PI / 32,
        },

        v: {
          min: 0,
          max: Math.PI * 2,
          step: Math.PI / 20,
        },

        x: function (u, v) {
          if (u < startRadian) {
            return (
              offsetX +
              Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
            );
          }
          if (u > endRadian) {
            return (
              offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
            );
          }
          return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
        },

        y: function (u, v) {
          if (u < startRadian) {
            return (
              offsetY +
              Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
            );
          }
          if (u > endRadian) {
            return (
              offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
            );
          }
          return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
        },

        z: function (u, v) {
          if (u < -Math.PI * 0.5) {
            return Math.sin(u);
          }
          if (u > Math.PI * 2.5) {
            return Math.sin(u);
          }
          return Math.sin(v) > 0 ? 1 * height : -1;
        },
      };
    },
    getPie3D(pieData, internalDiameterRatio) {
      let series = [];
      let sumValue = 0;
      let startValue = 0;
      let endValue = 0;
      let legendData = [];
      let k =
        typeof internalDiameterRatio !== "undefined"
          ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio)
          : 1 / 3;

      // 为每一个饼图数据，生成一个 series-surface 配置
      for (let i = 0; i < pieData.length; i++) {
        sumValue += pieData[i].value;

        let seriesItem = {
          name:
            typeof pieData[i].name === "undefined"
              ? `series${i}`
              : pieData[i].name,
          type: "surface",

          parametric: true,
          wireframe: {
            show: false,
          },
          pieData: pieData[i],
          pieStatus: {
            selected: false,
            hovered: false,
            k: k,
          },
          labelLine: {
            show: false,
          },
          label: {
            show: false,
            // normal: {
            //   position: "inner",
            //   formatter: (params) => {
            //     return params;
            //   },
            // },
          },
          itemStyle: {
            opacity: 1,
          },
        };

        if (typeof pieData[i].itemStyle != "undefined") {
          let itemStyle = {};

          typeof pieData[i].itemStyle.color != "undefined"
            ? (itemStyle.color = pieData[i].itemStyle.color)
            : null;
          typeof pieData[i].itemStyle.opacity != "undefined"
            ? (itemStyle.opacity = pieData[i].itemStyle.opacity)
            : null;

          seriesItem.itemStyle = itemStyle;
        }
        series.push(seriesItem);
      }

      // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
      // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
      for (let i = 0; i < series.length; i++) {
        let tmpH = 0;
        //判断高度
        if (series[i].name == "党委") {
          tmpH = 15;
        } else if (series[i].name == "人大") {
          tmpH = 10;
        } else if (series[i].name == "政府") {
          tmpH = 25;
        } else if (series[i].name == "政协") {
          tmpH = 5;
        } else if (series[i].name == "法院") {
          tmpH = 10;
        } else if (series[i].name == "检察院") {
          tmpH = 10;
        } else if (series[i].name == "群团") {
          tmpH = 2;
        } else if (series[i].name == "民主党派") {
          tmpH = 2;
        }
        endValue = startValue + series[i].pieData.value;
        series[i].pieData.startRatio = startValue / sumValue;
        series[i].pieData.endRatio = endValue / sumValue;
        series[i].parametricEquation = this.getParametricEquation(
          series[i].pieData.startRatio,
          series[i].pieData.endRatio,
          false,
          false,
          k,
          tmpH
        );

        startValue = endValue;

        legendData.push(series[i].name);
      }

      // 准备待返回的配置项，把准备好的 legendData、series 传入。
      const self = this;
      let option = {
        tooltip: {
          //   backgroundColor: "#053A8D",
          formatter: (params) => {
            if (params.seriesName !== "mouseoutSeries") {
              return `${
                params.seriesName
              }<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${
                params.color
              };"></span>${option.series[params.seriesIndex].pieData.value}`;
            }
          },
        },

        labelLine: {
          show: true,
        },
        label: {
          show: true,
        },
        legend: {
          data: legendData,
          textStyle: {
            color: "rgba(150,202,223)",
            fontSize: 12,
          },
          itemGap: 18,
          itemWidth: 10,
          itemHeight: 10,
          icon: "roundRect",
          formatter: function (name) {
            let datad = self.sydwdata;
            let total = 0;
            let tarValue;
            for (var i = 0; i < datad.length; i++) {
              total += datad[i].value;
              if (datad[i].name == name) {
                tarValue = datad[i].value;
              }
            }
            let v = tarValue;
            let p = Math.round((tarValue / total) * 100);
            return `${name} ${v} (${p}%)`;
          },
          left: "center",
          bottom: "5%",
        },
        xAxis3D: {
          min: -1.3,
          max: 1.3,
        },
        yAxis3D: {
          min: -1.3,
          max: 1.3,
        },
        zAxis3D: {
          min: -1.3,
          max: 1.3,
        },
        grid3D: {
          show: false,
          boxHeight: 5,
          top: "-12%",
          left: "-2%",
          // environment: "#021041",
          viewControl: {
            distance: 6000,
            alpha: 50,
            beta: 10,
          },
        },
        series: series,
      };
      return option;
    },

    async refreshData(depCode) {
      if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose(); //销毁
      }
      myChart = this.$echarts.init(document.getElementById("sydwpie"));
      myChart.showLoading("default", {
        text: "正在加载，请稍候...",
        color: "#c23531",
        textColor: "rgba(255, 255, 255, 0.5)",
        maskColor: "#00000000",
        zlevel: 0,
      });
      await Sever.smz
        .getSydwpie({ depCode: depCode })
        .then((res) => {
          if (res.code == 1) {
            //拼接总计
            let zj = res.data.zj.toString().split("");
            let zjstr = "总计：";
            for (let index = 0; index < zj.length; index++) {
              zjstr += "<span>" + zj[index] + "</span>";
            }
            this.sydwCount = zjstr;
            this.sydwdata = [
              {
                name: "党委",
                value: res.data.dw,
                itemStyle: { color: "#637FEA" },
                startRatio: 0,
                endRatio: 0.15,
              },
              {
                name: "人大",
                value: res.data.rd,
                itemStyle: { color: "#3919FB" },
                startRatio: 0.15,
                endRatio: 0.4,
              },
              {
                name: "政府",
                value: res.data.zf,
                itemStyle: { color: "#B35AFF" },
                startRatio: 0.4,
                endRatio: 0.5,
              },
              {
                name: "政协",
                value: res.data.zx,
                itemStyle: { color: "#5AADD4" },
                startRatio: 0.5,
                endRatio: 0.7,
              },
              {
                name: "法院",
                value: res.data.fy,
                itemStyle: { color: "#EDCC31" },
                startRatio: 0.5,
                endRatio: 0.7,
              },
              {
                name: "检察院",
                value: res.data.jcy,
                itemStyle: { color: "#FF8421" },
                startRatio: 0.5,
                endRatio: 0.7,
              },
              {
                name: "群团",
                value: res.data.qt,
                itemStyle: { color: "#15B309" },
                startRatio: 0.5,
                endRatio: 0.7,
              },
              {
                name: "民主党派",
                value: res.data.mzdp,
                itemStyle: { color: "#25BD97" },
                startRatio: 0.5,
                endRatio: 0.7,
              },
            ];
            this.initEcharts();
          } else {
            console.log("sydwpie接口请求错误！");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  computed: {
    changeData() {
      return this.$store.state.depCode;
    },
  },
  watch: {
    changeData: {
      handler(newV) {
        this.refreshData(newV);
      },
      // deep: true,
      // immediate: true,
    },
  },
};
</script>